<template>
  <div>
    <iframe ref="designIframe" title="" class="iframe_body"
            :src="realUrl" frameborder="0" width="100%"
            height="800px" scrolling="auto" />
  </div>
</template>

<script>
import { isExternal } from '@/framework/utils/validate'

export default {
  name: 'IframePageView',
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // id: ''
      path: ''
    }
  },

  computed: {
    realUrl() {
      // return 'http://localhost:8100/'
      // 外部链接
      if (isExternal(this.url)) {
        return this.url
      } else { // 内部链接 必须以/开头
        return `${process.env.VUE_APP_TARGET}${this.url}`
      }
    },
    visitedViews() {
      return this.$store.state.tagsView.visitedViews
    }
  },
  created() {
  },
  mounted() {
    if (this.$route.query.path) {
      window.addEventListener('message', this.handleMessage)
    }
    const { id } = this.$route.query

    this.$nextTick(() => {
      // 获取iframe元素
      // const iframe = document.getElementById('designIframe')
      const iframe = this.$refs['designIframe']
      iframe.onload = function (e) {
        // 通过.contentWindow.postMessage(data,"*")向iframe子组件传值
        const content = iframe.contentWindow
        if (id) {
          content.postMessage({
            cmd: 'editPage',
            params: {
              id
            }
          }, '*')
        } else {
          content.postMessage({
            cmd: 'addPage'
          }, '*')
        }
      }
    })
  },
  beforeDestroy() {
    window.removeEventListener('message', this.handleMessage)
  },
  methods: {
    handleMessage(event) {
      const { data } = event
      if (data.cmd === 'closePage') {
        // this.$router.go(-1)
        // this.$router.replace(this.$route.query.path)
        const nowtag = this.visitedViews.filter((item) => {
          if (item.path === this.$route.path) return item
        })
        this.$store.dispatch('tagsView/delView', nowtag[0])
        this.$router.go(-1)
        if (data.params.showMessage) {
          this.$message.success(this.$route.query.id ? '修改成功' : '新增成功')
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .iframe_body{
    padding: 10px;
    background: #fff;
  }
</style>
